import type { Directive } from "vue";

const scrollAnimate: Directive = {
  mounted(el: HTMLElement, binding) {
    const className = binding.value || "fade-in"; // 默认类名
    el.style.visibility = "hidden"; // 初始不可见

    const observer = new IntersectionObserver(
      ([entry]) => {
        if (entry.isIntersecting) {
          el.classList.add(className);
          el.style.visibility = "visible";
          observer.unobserve(el); // 只触发一次
        }
      },
      {
        threshold: 0.1
      }
    );

    observer.observe(el);
    (el as any)._observer = observer;
  },
  unmounted(el: any) {
    el._observer?.disconnect();
  }
};

export default scrollAnimate;
